<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href="../css/bootstrap.min.css">
    <link rel="stylesheet" href="../plugins/fontawesome-free/css/all.min.css">
    <link rel="stylesheet" href="../plugins/layui/css/layui.css">
    <script src="../plugins/jquery/jquery.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <script src="../plugins/layui/layui.js"></script>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="../plugins/fontawesome-free/css/all.min.css">
    <style>
        .top-btn {
            margin-top: 10px;
        }

        .top-content {
            text-align: center;
        }
    </style>
</head>

<body>
<div class="layui-container">
    <div class="top-content">
        <button class='top-btn layui-btn layui-btn-primary' data-toggle='modal' data-target='#modal3'>添加角色</button>
    </div>
    <table class="layui-hide" id="test" lay-filter="role">
        <!--                            管理角色资源模态框-->
        <div class="modal fade" id="modal" tabindex="-1" role="dialog"
             aria-labelledby="exampleModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <label>资源信息维护</label>
                    </div>
                    <div class="modal-body">
                        <div id="powertree"></div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                        </button>
                        <button type="button" class="btn btn-default" onclick="sub()">提交
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <!--                            管理角色资源模态框./-->
    </table>

</div>
<!--                            修改模态框-->
<div class="modal fade" id="modal2" tabindex="-1" role="dialog"
     aria-labelledby="exampleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <label>修改</label>
            </div>
            <div class="modal-body">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <label class="layui-form-label">角色名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="title" autocomplete="off" id="rname_u" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">角色描述</label>
                        <div class="layui-input-block">
                            <input type="text" name="title" autocomplete="off" id="remark_u" class="layui-input">
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
                <button type="button" class="btn btn-default" data-type="reload" onclick="update()">修改
                </button>
            </div>
        </div>
    </div>
</div>
<!--                            修改模态框./-->
<!--                            添加模态框-->
<div class="modal fade" id="modal3" tabindex="-1" role="dialog"
     aria-labelledby="exampleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <label>添加角色</label>
            </div>
            <div class="modal-body">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <label class="layui-form-label">角色名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="title" autocomplete="off" id="rname_a"
                                   class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">角色描述</label>
                        <div class="layui-input-block">
                            <input type="text" name="title" autocomplete="off" id="remark_a"
                                   class="layui-input">
                        </div>
                    </div>

                </form>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
                <button type="button" class="btn btn-default" id="addrole">添加
                </button>
            </div>
        </div>
    </div>
</div>
<!--                            添加模态框./-->

<script type="text/html" id="barDemo">
    <button type='button' class='layui-btn-sm layui-btn layui-btn-primary' lay-event="update" >
        <i class='fas fa-wrench'></i></button>
    <button type='button' class='layui-btn-sm layui-btn layui-btn-primary' lay-event="delete">
        <i class='fas fa-trash-alt'></i></button>
    <button type='button' class='layui-btn-sm layui-btn layui-btn-primary' lay-event="manage">
        管理角色对应资源
    </button>

</script>
<script>

    var sub;
    var update;

    $("#addrole").on("click",function (){
        let rname_a = $("#rname_a").val();
        let remark_a = $("#remark_a").val();
        $.ajax({
            url:"addRole",
            dataType:"json",
            data:{
                "rname":rname_a,
                "remark":remark_a
            },
            success: function(resp){
                if (resp===1) {
                    layer.msg("添加成功",{icon:3})
                }else{
                    layer.msg("添加失败",{icon:3})
                }
            }
        })
    })

    layui.use(['table', 'tree'], function () {
        var table = layui.table;
        var tree = layui.tree;
        let datas = []
        let checked = []//树形图选中的
        var treedate;

        function getAllRoles() {
            $.ajax({
                url: "getroles",
                dataType: "json",
                success: function (resp) {
                    datas = resp
                }
            })

            setTimeout(function () {
                table.render({
                    elem: '#test'
                    ,id:"test"
                    // , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    , cols: [[ //表头
                        {field: 'rid', title: '编号', sort: true, fixed: 'left'}
                        , {field: 'rname', title: '名称'}
                        , {field: 'remark', title: '描述'}
                        , {fixed: 'right', title: '操作', align: 'center', toolbar: '#barDemo'}
                    ]]
                    , data: datas
                    , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                        layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                        , groups: 3 //只显示 1 个连续页码
                        , first: false //不显示首页
                        , last: false //不显示尾页
                        , limit: 4
                    }
                    , height: '236'
                });
            }, 500)

        }

        setTimeout(function () {
            //延迟加载
            getAllRoles()
        }, 100);


        table.on('tool(role)', function (obj) { // 注：test 是 table 原始标签的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

            if (layEvent === "delete") {

                layer.confirm('确定删除吗？', {
                    btn: ['删除','取消'] //按钮
                }, function(){
                    $.ajax({
                        url: 'delrole/' + data.rid,
                        dataType: 'json',
                        success: function (resp) {
                            if (resp === 1) {
                                location.reload()
                            }else{
                                layer.msg("删除失败，请检查是否绑定有资源",{icon:2})
                            }
                        }
                    })
                }, function(){

                });

            } else if (layEvent === "manage") {
                $('#modal').modal('show')

                function getPowers() {

                    let allpower = []
                    $.ajax({
                        url: "getpowers/" + data.rid,
                        dataType: "json",
                        success: function (data) {
                            console.log(data)
                            allpower = data
                        }
                    })
                    setTimeout(function () {
                        //渲染
                        var inst1 = tree.render({
                            elem: '#powertree'  //绑定元素
                            , id: "tree1"
                            , data: [{title: '根目录', children: allpower, id: 0, checked: false, spread: true}]
                            , showCheckbox: true
                        });

                    }, 100)
                }

                setTimeout(getPowers, 100)

                sub = function () {

                    treedate = tree.getChecked('tree1');
                    console.log(treedate)
                    var nodeIds = new Array();
                    nodeIds = getCheckedId(treedate);
// 测试
                    var permList = nodeIds;
                    console.log("permList:" + permList);

// 获取选中节点的id
                    function getCheckedId(jsonObj) {
                        var id = "";
                        $.each(jsonObj, function (index, item) {
                            if (id != "") {
                                id = id + "," + item.id;
                            } else {
                                id = item.id;
                            }
                            var i = getCheckedId(item.children);
                            if (i != "") {
                                id = id + "," + i;
                            }
                        });
                        return id;
                    }

                    $.ajax({
                        url: "returnIds/" + data.rid,
                        dataType: "json",
                        data: {
                            permList: permList
                        },
                        success: function () {

                        }
                    })

                }

            }else if(layEvent ==="update"){
                $('#modal2').modal('show')

                function load() {
                    //查询数据库填充表单
                    $.ajax({
                        url:"getroleByRid/"+data.rid,
                        dataType:"json",
                        success:function(resp){
                            $('#rname_u').val(resp.rname)
                            $('#remark_u').val(resp.remark)
                        }
                    })

                }

                setTimeout(load, 500)

                update=function (){
                //修改
                    let rname = $('#rname_u').val();
                   let remark =$('#remark_u').val()
                    $.ajax({
                        url:"updateroleByRid/"+data.rid,
                        dataType:"json",
                        data:{
                            rname:rname,
                            remark:remark
                        },
                        success:function(resp){
                            if(resp===1){
                                layer.msg("修改成功",{icon:3})
                                location.reload()
                            }else{
                                layer.msg("修改失败",{icon:3})
                            }
                        }
                    })
                }
            }
            //   -----------。/事件------------
        });

    });


</script>
</body>

</html>